package com.dubbo.soa.spring.parse;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class ReferenceBeanDefinitionParse implements BeanDefinitionParser {
    private Class<?> beanClass;
    public ReferenceBeanDefinitionParse(Class<?> beanClass){
        this.beanClass = beanClass;
    }
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        //element对象传到reference，并交由spring管理
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
        rootBeanDefinition.setBeanClass(beanClass);
        rootBeanDefinition.setLazyInit(false);
        String id = element.getAttribute("id");
        String intf = element.getAttribute("interface");
        String check = element.getAttribute("check");
        String protocol = element.getAttribute("protocol");
        if(id != null && !"".equals(id)){
            if(parserContext.getRegistry().containsBeanDefinition(id)){
                throw new IllegalStateException("spring has this id");
            }
            rootBeanDefinition.getPropertyValues().add("id",id);
        }else {
            //假如id没有配置，id生成策略
            id = beanClass.getName().substring(0,1).toLowerCase()+
                    beanClass.getName().substring(1);
            rootBeanDefinition.getPropertyValues().add("id",id);


        }
        if (intf == null || "".equals(intf)){
            throw new IllegalStateException("interface不能为空");
        }else {
            rootBeanDefinition.getPropertyValues().add("intf",intf);
        };
        if(check == null || "".equals(check)){
            throw new IllegalStateException("check不能为空");
        }else{
            rootBeanDefinition.getPropertyValues().add("check",check);
        }
        //创建出来的rootBeanDefinition必须交由spring管理
        parserContext.getRegistry().registerBeanDefinition(id,rootBeanDefinition);
        return rootBeanDefinition;
    }
}
